import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../features/training_records/bloc/training_history_bloc.dart';
import '../features/training_records/bloc/training_history_event.dart';
import '../features/training_records/bloc/training_history_state.dart';
import '../features/training_records/model/training_record.dart';

class DotTrainingResultPage extends StatefulWidget {
  final List<bool> correctness;
  final List<int> responseTimes;

  const DotTrainingResultPage({
    super.key,
    required this.correctness,
    required this.responseTimes,
  });

  @override
  State<DotTrainingResultPage> createState() => _DotTrainingResultPageState();
}

class _DotTrainingResultPageState extends State<DotTrainingResultPage> {
  @override
  void initState() {
    super.initState();
    // 页面初始化时自动保存训练记录
    WidgetsBinding.instance.addPostFrameCallback((_) => _autoSaveTrainingRecord());
  }

  void _autoSaveTrainingRecord() {
    print('Starting automatic dot training record creation...');
    final correctCount = widget.correctness.where((c) => c).length;
    final totalCount = widget.correctness.length;
    final duration = widget.responseTimes.fold(0, (sum, time) => sum + time);

    print('Dot training stats - correct: $correctCount, total: $totalCount, duration: $duration ms');

    final record = TrainingRecord(
      type: 'dot',
      correctCount: correctCount,
      totalCount: totalCount,
      durationMs: duration,
      timestamp: DateTime.now(),
    );

    print('Created dot training record: ${record.toString()}');
    context.read<TrainingHistoryBloc>().add(TrainingRecordAdded(record));
    print('Dispatched TrainingRecordAdded event for dot training');
  }

  @override
  Widget build(BuildContext context) {
    final correctCount = widget.correctness.where((c) => c).length;
    final totalCount = widget.correctness.length;
    final accuracy = totalCount > 0 ? (correctCount / totalCount) * 100 : 0;
    final duration = widget.responseTimes.fold(0, (sum, time) => sum + time);
    final minutes = duration ~/ 60000;
    final seconds = (duration % 60000) ~/ 1000;

    return Scaffold(
      appBar: AppBar(
  title: const Text('训练结果'),
  leading: IconButton(
    icon: const Icon(Icons.arrow_back),
    onPressed: () => Navigator.popUntil(context, (route) => route.isFirst),
  ),
),
      body: SafeArea( // 添加安全区域包裹
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(16),
          child: Column(
            children: [
              const SizedBox(height: 16),
              _buildResultIndicator(accuracy.toDouble()),
              const SizedBox(height: 16),
              _buildStatsGrid(correctCount, totalCount, minutes, seconds),
              const SizedBox(height: 24),
              // 移除BlocListener的导航逻辑，改为按钮手动触发
              ElevatedButton.icon(
                onPressed: () => Navigator.popUntil(context, (route) => route.isFirst), 
                icon: const Icon(Icons.check_circle),
                label: const Text('记录已自动保存，返回训练'),
                style: ElevatedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
                  textStyle: const TextStyle(fontSize: 16),
                ),
              ),
              const SizedBox(height: 16),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildResultIndicator(double accuracy) {
    return Column(
      children: [
        Text(
          '${accuracy.toStringAsFixed(1)}%',
          style: TextStyle(
            fontSize: 72,
            fontWeight: FontWeight.bold,
            color: accuracy >= 80 ? Colors.green : accuracy >= 60 ? Colors.orange : Colors.red,
          ),
        ),
        const SizedBox(height: 16),
        Text(
          accuracy >= 80 ? '太棒了！' : accuracy >= 60 ? '继续努力！' : '加油哦！',
          style: const TextStyle(fontSize: 24, color: Colors.grey),
        ),
      ],
    );
  }

  Widget _buildStatsGrid(int correct, int total, int minutes, int seconds) {
    return GridView.count(
      shrinkWrap: true,
      crossAxisCount: 2,
      crossAxisSpacing: 8,  // 减少水平间距
      mainAxisSpacing: 8,   // 减少垂直间距
      childAspectRatio:  1.333,  // 增加宽高比，使卡片更扁平
      children: [
        _buildStatCard(Icons.check, '正确题数', '$correct/$total'),
        _buildStatCard(Icons.timer, '用时', '${minutes}分${seconds}秒'),
        _buildStatCard(Icons.trending_up, '正确率', '${(correct/total*100).toStringAsFixed(1)}%'),
        _buildStatCard(Icons.insights, '平均反应', '${(widget.responseTimes.fold(0, (sum, t) => sum + t) / widget.responseTimes.length).toStringAsFixed(0)}ms'),
      ],
    );
  }

  Widget _buildStatCard(IconData icon, String title, String value) {
    return Card(
      elevation: 4,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(12), // 减少内边距
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(icon, size: 28, color: Colors.blue), // 减小图标尺寸
            const SizedBox(height: 6), // 减少图标与文字间距
            Text(title, style: const TextStyle(fontSize: 14, color: Colors.grey)), // 减小标题字号
            const SizedBox(height: 2), // 减少标题与数值间距
            Text(value, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), // 减小数值字号
          ],
        ),
      ),
    );
  }

}

